<template>
    <el-form ref="registerFormRef" :model="state.registerUserData" :rules="registerRules" label-width="100px"
        class="registerForm sign-up-form">
        <el-form-item label="用户名" prop="name">
            <el-input v-model="state.registerUserData.name" placeholder="Enter UserName..."></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="state.registerUserData.email" placeholder="Enter Email..."></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="state.registerUserData.password" type="password" placeholder="Enter Password...">
            </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
            <el-input v-model="state.registerUserData.password2" type="password" placeholder="Enter Password...">
            </el-input>
        </el-form-item>

        <el-form-item label="选择身份">
            <el-select v-model="state.registerUserData.role" placeholder="请选择身份">
                <el-option label="管理员" value="admin"></el-option>
                <el-option label="用户" value="user"></el-option>
                <el-option label="游客" value="visitor"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button @click="handleRegister(registerFormRef)" type="primary" class="submit-btn">注册</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { FormInstance, ElMessage } from "element-plus";
import { ref, defineProps, getCurrentInstance, defineEmits, reactive } from "vue";
import { useRouter } from "vue-router";
// import axios from 'axios' // 仅限在当前组件使用
defineProps({
    registerUser: {
        type: Object,
        required: true,
    },
    registerRules: {
        type: Object,
        required: true,
    },
});
const proxy = getCurrentInstance() as any;

let state = reactive<any>(
    {
        registerUserData: proxy.ctx.registerUser
    }
)
const emit = defineEmits(['update:signUpMode']);
const registerFormRef = ref<FormInstance>();
//@ts-ignore
//@ts-ignore
const { $axios } = proxy.appContext.config.globalProperties
//注册
const handleRegister = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid: boolean) => {
        if (valid) {
            $axios.post("/api/v1/auth/register",
                state.registerUserData
            ).then((res: any) => {
                console.log(res);
                if (res.success) {
                    ElMessage.success('注册成功');
                    setTimeout(() => {
                        emit('update:signUpMode');
                        state.registerUserData = {}
                    }, 1000)
                }
            })
        } else {
            console.log("error submit!!");
            return false;
        }
    });
};
</script>
<style scoped>
</style>